<?php
/**
 * Manager phone 
 */
class CustomerController extends Controller
{

	public $layout='//layouts/customerDefault';

	/**
	 * methodDescription.
	 *
	 * @return returnType returnDescription
	 */
	public function filters() {
		return array(
	    	'accessControl',
		//'checkAccess',
		);

	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow', // allow all users to perform 'index' and 'view' actions
			'actions' => array('login','test','AjaxLoadCustomer', 'debug'),
			'users'   => array('*'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('view','login','summary','managerPhone', 'makePayment', 
								 'paymentHistory','callDetail','speedDial','didDirect','followMe',
								 'editProfile','changePassword', 'logOut','paymentError', 'paymentReturnUrl',
								 'paymentComplete'),
				'users'  =>array('@'),
		),
		array('allow', 
				'actions'=>array('create','update',),
				'users'  =>array('@'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'  =>array('admin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}
	
	public function actionDebug()
	{
        
		$db = Yii::app()->enticedb;
		$sql = "SELECT COUNT(*) FROM POST3.ep_to_user_def WHERE value='1234567891' and CUST_ID ='".CGlobal::$wsCustID."'";
		$data = $db->createCommand($sql)->queryAll();
		echo '<pre>';
		print_r($data); die;
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$this->layout = 'customerLogin';
		$model        = new CustomerLoginForm();

		// collect user input data
		if(isset($_POST['CustomerLoginForm']))
		{
			$model->attributes = $_POST['CustomerLoginForm'];

			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			{
				$this->redirect($this->createUrl('customer/summary', array('lang' => $this->language)));
			}

		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logout and come back home url.
	 */
	public function actionLogout() 
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	/**
	 * Show summary page about current account.
	 */
	public function actionSummary() 
	{
		$user          = Yii::app()->user;
		$currentCredit = 0;
		$username      = $user->getState('username');
		$accountNumber = $user->getState('accountNumber');

//		$cusPayment    = TblCustomerPayment::model()->findByAttributes(array('customerID' => $user->getState('customerID')), array('order' => 'createdDate desc'));
//		if($cusPayment)
//			$currentCredit =$cusPayment->chargedAmount;
		$currentCredit = $user->getState('currentCredit', 0.0);
	
		
		
		$this->render('summary', array(
	    	'username'      => $username,
	    	'currentCredit' => $currentCredit,
	    	'accountNumber' => $accountNumber,
		));
	}

	/**
	 * Thêm, xóa số điện thoại.
	 * @return returnType returnDescription
	 */
	public function actionManagerPhone() 
	{
		$user          = Yii::app()->user;
		$subscriber_id = Yii::app()->user->getState('accountNumber');
		$rawData       = EnticeWS::getANIPhones($subscriber_id); 
				
		$dataProvider = new CArrayDataProvider($rawData, array(
				'pagination'=>array(
		        	'pageSize'=>CGlobal::$phonePageSize,
				),
		));

		$model = new AddPhoneForm();

		// collect user input data
		if(isset($_POST['AddPhoneForm']))
		{
			$model->attributes=$_POST['AddPhoneForm'];//bind value from form to model
			// validate user input and redirect to the previous page if valid
			
			try
			{
				/**
				 * Normal $model->save() also validate but. AddPhoneForm is my model. So I must validate by hand.
				 */
				if($model->validate() && $model->save())
				{
					$this->redirect($this->createUrl('customer/managerPhone', array('lang' => $this->language)));
				}
			}
			catch (Exception $e)
			{
				$model->addError('UpdateAniSubscriber', $e->getMessage());
			}
			
		}

		//Delete and show error on flash
		if(isset($_POST['DeletePhoneForm']) && $_POST['DeletePhoneForm'] === 'true')
		{
			$phone            = Yii::app()->request->getParam('number', 0);
			$deletePhoneFlash = '';

			
			if($model->delete($phone))
			{
				$deletePhoneFlash = "Delete phone successfull!";
				Yii::app()->user->setFlash('delete-phone-success',$deletePhoneFlash);
			}
			else
			{
				$deletePhoneFlash = "Delete phone fail!";
				Yii::app()->user->setFlash('delete-phone-fail',$deletePhoneFlash);
			}

			$this->redirect($this->createUrl('customer/managerPhone', array('lang' => $this->language)));
		}

		$this->render('managerPhone', array(
	    	'dataProvider' => $dataProvider,
	    	'model'        => $model,
		));
	}

	/**
	 * process payment by authorize.net or paypal.
	 *
	 * @return flash on swf_viewport(xmin, xmax, ymin, ymax)
	 */
	public function actionMakePayment() {

		$model = new TblCustomerPayment();
		$model->creditExpireYear   = date('Y');
		$model->creditExpireMonth  = date('m');

		$subscriber_id = Yii::app()->user->getState('accountNumber');
		$message       = NULL;
		$info          = NULL;

		if(Yii::app()->request->isPostRequest && isset($_POST['payment_method']))
		{
			$payment_method = $_POST['payment_method'];
			if($payment_method == 'cc')
			{
				$model->checkbox   = $_POST['TblCustomerPayment']['checkbox'];
				$model->attributes = $_POST['TblCustomerPayment'];

				if($model->validate())
				{
					$info = MyPayment::CreditCardCharge_SP($model);//
					
					if($info['success'] == true)
					{

						$model->customerID      = Yii::app()->user->getState('customerID');
						$model->seqNo           = TblCustomerPayment::getSeqNo($model->customerID);
						$model->createdDate     = date('Y-m-d H:i:s');
						$model->chargedBy       = 'USER SITE';
						$model->paymentMethodID = '1';
						
						$dbTransaction = Yii::app()->db->beginTransaction();
						try
						{
							if($model->save())
							{
								
								$orcTransaction = Yii::app()->orcdb->beginTransaction();
								try 
								{
									//insert code into oracle database
									$amount = $model->chargedAmount;
									$date   = date('m/d/Y H:i:s');

									$sql    = "UPDATE USER_DEF SET OUTSTANDING_BALANCE = OUTSTANDING_BALANCE + '$amount'  WHERE USER_ID = '$subscriber_id'";
									Yii::app()->orcdb->createCommand($sql)->execute();
									
									$sql="UPDATE user_def SET balance = balance + '$amount', ACT_DATE = SYSDATE WHERE user_id = '$subscriber_id'";
									Yii::app()->orcdb->createCommand($sql)->execute();
									
									$payment = new PAYMENT;
									$payment->PAYMENT_ID     = new CDbExpression('PAYMENT_ID_SEQ.NextVal');
									$payment->PAYER_ID       = $subscriber_id;
									$payment->RECEIPTER      = 'Bao';
									$payment->DESCRIPTION    = 'No description';
									$payment->PAYMENT_DATE   = date('m/d/Y H:i:s');
									$payment->PAYER_ID_TYPE  = 4;
									$payment->PAYMENT_AMOUNT = $amount;
									$payment->PAYMENT_TYPE   = 4;
									$payment->CHECK_NO       = 0;
									
									$ok = $payment->save(false);

									if(!$ok)
									{
										throw new CDbException("Cannot save infomation about payment amount");
									}
									else
									{
										$orcTransaction->commit();	//post3 commit
									}
									
								}
								catch(CDbException $e)
								{
									$orcTransaction->rollback();
									throw new CDbException($message);	
								}

								$dbTransaction->commit();//sqlserver commit
							}
							else
							{
								Yii::app()->user->setFlash('makepayment-error', "CreditCard Transaction error!");
								$this->redirect(array('Customer/makePayment', 'lang' => $this->language));
							}

							
							
						}
						catch (CDbException $e)
						{
							$dbTransaction->rollback();
							Yii::app()->user->setFlash('makepayment-error', 'Make payment fail!'."\n".$e->getMessage());
						}
						
					}
				}
					
			}
			elseif($payment_method == 'paypal')
			{
				$base_url= Helper::param('BASE_URL');
				$amount  = $_POST['TblCustomerPayment']['chargedAmount'];

				if((int)$amount >= 20 )
				{
					$paypalURL  = '&L_NAME0='.Helper::param('PAYPAL_ITEM_NAME');
					$paypalURL .='&L_AMT0='.$amount;
					$paypalURL .='&L_QTY0=1';
					$paypalURL .='&ITEMAMT='.$amount;
					$paypalURL .='&AMT='.$amount;
					$paypalURL .= '&CURRENCYCODE='.Helper::param('PAYPAL_CURRENCY_CODE');
					$paypalURL .= '&PAYMENTACTION=Sale';
					$paypalURL .= '&HDRIMG='.Helper::param('PAYPAL_IMAGE_LOGO');
					$paypalURL .= '&RETURNURL='.$this->createAbsoluteUrl('Customer/PaymentReturnUrl');
					$paypalURL .= '&CANCELURL='.$this->createAbsoluteUrl('Customer/PaymentCancel');

					$nvpstr                         = $paypalURL;
					$p                              = new Paypal();
					$resArray                       = $p->hash_call("SetExpressCheckout",$nvpstr);
					Yii::app()->session['resArray'] = $resArray;

					//var_dump($resArray, $paypalURL); die;
					$ack = strtoupper($resArray["ACK"]);

					if($ack =="SUCCESS")
					{
						$token     = urldecode($resArray["TOKEN"]);
						$paypalURL = Helper::param('PAYPAL_URL_TEST').$token;
						$this->redirect($paypalURL);
					}
					else
					{
						$this->redirect(array('Customer/PaymentError','lang' => $this->language));
					}
				}
				
				$message=Yii::t('message',"Amount must be greater or equal than 20$");
				Yii::app()->user->setFlash('makepayment-notice', $message);
				
				$model->chargedAmount = $amount;//keep status for form 
				Yii::app()->clientScript->registerScript( 'hide_cc','$("#show_box").hide();$("#paypal").attr("checked",true);');
			}

			
			if($info['success'] == true)
			{
				Yii::app()->user->setFlash('makepayment-success', $message);
				$this->redirect(array('PaymentHistory', 'lang' => $this->language));
			}
			
			elseif($info['success'] == false)
			{
				Yii::app()->user->setFlash('makepayment-error', $info['reason']);
			}
		}

		$this->render('makePayment', array(
	    	'model' => $model,
		));
	}

	/**
	 * Pagination payment history. Because payment save in sqlserver.
	 *
	 * @return render View
	 */
	public function actionPaymentHistory() {
		//make dataprovider tbl_CustomerPayment có customerID = current user đăng nhập
		$user     = Yii::app()->user;
		
		$criteria = new CDbCriteria;
		$criteria->compare("customerID", $user->getState('customerID'));
		$criteria->order = 'createdDate ASC';
		
		$dataProvider = new CActiveDataProvider('TblCustomerPayment', array(
			'criteria'  => $criteria,
			'pagination'=>array(
	        	'pageSize'=>CGlobal::$paymentHisPageSize,
			),
		));
		
		$this->render('paymentHistory', array(
	    	'dataProvider' => $dataProvider,
		));
		
	}

	/**
	 * Get data from oracle database.
	 *
	 * @return render View
	 */
	public function actionCallDetail() {
		
		$subscriber_id = Yii::app()->user->getState('accountNumber');
		
		$criteria = new CDbCriteria();
		$criteria->compare('PPRUserID', $subscriber_id);
		$criteria->order = 'SeizeDateTime DESC';

		$dataProvider = new CActiveDataProvider('WSCALLCURRENT', array(
			'criteria'   => $criteria,
			'pagination' => array(
		    	'pageSize'=>CGlobal::$callDetailPageSize,
			),
		));
		
		$this->render('callDetail', array(
	    	'dataProvider' => $dataProvider,
		));
	}

	/**
	 * Add speeddial to entice database on server
	 *
	 * @return renderView
	 */
	public function actionSpeedDial() {
		$user = Yii::app()->user;

		if(isset($_POST['UpdateSpeedDialForm']))
		{
			$isUpdate = true;
			$model    = SUBFEATUREPARM::model()->findByAttributes(array('F_PARM' => $_POST['id']));
			$model->bindData();//fetch data to country_code + phone_number
		}
		else
		{
			$model    = new SUBFEATUREPARM;
			$isUpdate = false;
		}
		//$rawData = TblSpeedDial::model()->findByAttributes(array('customerID' => $user->getState('customerID')));

		$criteria = new CDbCriteria;
		$criteria->compare("MAIN_NUMBER", $user->getState('accountNumber')); //main_number is subscriber_id
		$criteria->order = "F_PARM asc";

		$dataProvider = new CActiveDataProvider('SUBFEATUREPARM', array(
				'criteria'   => $criteria,
				'pagination' => array(
					'pageSize' => CGlobal::$speedDialPageSize,
				),
			)
		);

		//ADD+UPDATE SPEEDDIAL
		if(isset($_POST['SUBFEATUREPARM']))
		{
			$model->attributes = $_POST['SUBFEATUREPARM'];
			$model->FEATURE    = 1;

			//UPDATE
			if(!$isUpdate)
			{
				$model->scenario = 'add'; //When update we don't need check unique speed-dial. So we direct add scenario
			}

			if($model->validate() && $model->save())
			{
				if($isUpdate)
				{
					Yii::app()->user->setFlash('speeddial-success', 'Update phone successfully!');
				}
				else
				{
					Yii::app()->user->setFlash('speeddial-success', 'Add phone successfully!');
				}

				$this->redirect(array('speedDial', 'lang' => $this->language));
			}
		}

		//DELETE SPEEDDIAL
		if(isset($_POST['DeleteSpeedDialForm']))
		{
			$id    = Yii::app()->request->getParam('id', -1);
			$model = SUBFEATUREPARM::model()->findByAttributes(array('F_PARM' => $id));
			
			//var_dump($model); die;
			if($model->delete())
			{
				Yii::app()->user->setFlash('speeddial-success', 'Delete phone successfully!');
			}
			else
			{
				Yii::app()->user->setFlash('speeddial-error', 'Delete phone fail!'.$model->getErrors());
				var_dump($model->getErrors()); die;
			}
			$this->redirect(array('speedDial', 'lang' => $this->language)); //END
		}

		$this->render('speedDial', array(
	    	'dataProvider' => $dataProvider,
	    	'model'        => $model,
	    	'isUpdate'     => $isUpdate,
		));
	}

	//'didDirect','followMe','editProfile','changePassword'
	/**
	* methodDescription.
	*
	* @return returnType returnDescription
	*/
	public function actionDidDirect() {
		$this->render('didDirect');
	}

	public function actionFollowMe() {
		$this->render('followMe');
	}

	/**
	  * Add information profile about current Customer in sqlserver database
	  * @return renderView
	  */
	public function actionEditProfile($customerID) {

		$model = TblCustomerProfile::model()->findByPk($customerID);
		
		if($model == null)
		{
			throw new CHttpException(404,'The requested page does not exist.');
		}

		if(isset($_POST['TblCustomerProfile']))
		{
			$model->attributes=$_POST['TblCustomerProfile'];
			if($model->validate() && $model->save())
			{
				Yii::app()->user->setFlash('editprofile-success', 'Edit profile successfully!');
				$this->redirect(array('editProfile','customerID'=>$model->customerID));
			}
		}

		$this->render('editProfile',array(
			'model'=>$model,
		));
	}

	/**
	  * Change password in sqlserver database
	  */
	public function actionChangePassword() {

		$model = new ChangePasswordForm;
		if(isset($_POST['ChangePasswordForm']))
		{
			$model->attributes = $_POST['ChangePasswordForm'];
			if($model->validate() && $model->save())
			{
				Yii::app()->user->setFlash('changepass-success', 'Change password successfully!');
				$this->redirect(array('changePassword'));
			}
		}

		$this->render('changePassword', array(
	    	'model' => $model,
		));
	}

	/**
	 * Test funciton.
	 *
	 * @return returnType returnDescription
	 */
	public function actionTest() {

		/**
		 * make oracle customer
		 */
//		$orcCustomer = new OrcCustomer('4646664646');
//		echo "<pre>";
//		print_r($orcCustomer);
//		echo "</pre>";
		
		
		//SELECT
//		$sql = "select * from user_def where rownum<=1";
//		$command = Yii::app()->orcdb->createCommand($sql);
//		var_dump($command->queryRow());

//		$model = USERDEF::model()->findByAttributes(array('RESELLER_ID' => 12));
//		var_dump($model);
//
//		//INSERT
//		$model = new USERDEF();
//		$model->ACCT_ID =219;
//		$model->CUST_ID = 4128;
//		$model->CREATED_BY = 'Bao';
//		$model->CREATION_DATE = date('m/d/Y H:i:s');
//		$model->PIN = null;
//		$model->ACT_DATE = '23-NOV-11';
//		$model->PREPAID_CARD_SEQ = 0122010201;
//		
//		
//		$model->CREATED_BY = 'rashid';
//		$model->PIN = 0;
//		$model->BALANCE = 6;
//		$model->BALANCE_REF = 0;
//		$model->PLAY_TYPE = 1;
//		$model->PLAYED_FLAG = 0;
//		$model->STATUS = 6;
//		$model->ACT_DATE = date('m/d/Y H:i:s');
//		$model->TTL = 6;
//		$model->RESELLER_ID = 12;
//		$model->ERR_COUNTER =0; 
//		$model->LIMIT = 6;
//		$model->PREPAID_CARD_SEQ = 021900000001;
//		$model->MAX_ONLINE_CALLS = 0;
//		$model->ONLINE_CALLS = 0;
//		$model->TIME_USAGE_INT = 0;
//		$model->TIME_USAGE_DOM = 0;		
//		$model->TIME_USAGE_MOB = 0;
//		$model->TIME_USAGE_LOC = 0;
//		$model->MISCFEATURE_FLAG = 0;
//		$model->CALL_COUNTER = 0;
//		$model->OUTSTANDING_BALANCE = 0;
//		$model->ACCESS_CODE_ALWAYS = 0;
//		$model->APPFLAG = 0;
//		$model->FACE_VALUE = 6;
//		$model->CARD_NUMBER = 7403528891;
//
//		
//		
//		if($model->save())
//		{
//			echo 'Ok';
//		}
		
		//$sql = "select * from user_def where RESELLER_ID = '12'";

//		$command = Yii::app()->orcdb->createCommand($sql);
//		var_dump($command->queryAll());

		//$sql = "select * from ep_to_user_def";
		//$command = Yii::app()->orcdb->createCommand($sql);
		//var_dump($command->queryRow()); die;
		
	}

	/**
	 * Payment complete. Not in user. This is code of MR.Tuyen. email: 
	 *
	 * @return returnType returnDescription
	 */
	public function actionPaymentComplete() {

		if(!Yii::app()->request->isPostRequest){
			$this->redirect(array('Customer/Index'));	
		}
		
		$token         = urlencode(Yii::app()->session->get('token'));
		$paymentAmount = Yii::app()->session->get('TotalAmount');
		$paymentType   = 'sale';
		$currCodeType  = 'USD';
		$payerID       = urlencode(Yii::app()->session->get('payer_id'));
		$serverName    = Yii::app()->request->userHostAddress;		
		$nvpstr        ='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;
		$serverName    = 'hello';
		$p             = new Paypal();
		$resArray      = $p->hash_call("DoExpressCheckoutPayment",$nvpstr);
		$ack           = strtoupper($resArray["ACK"]);
		
		if($ack != 'SUCCESS' && $ack != 'SUCCESSWITHWARNING'){
			Yii::app()->session['reshash']=$resArray;
			$this->redirect(array('Customer/PaymentError'));
      	}
      
      	$message='';
    
//	      $_return=Payment::ChargeAccount_SP(Yii::app()->user->AccountId,Yii::app()->user->id,$resArray['TRANSACTIONID'],$paymentAmount,2,Yii::app()->user->LocalPhone);
//			  $message=Payment::ReturnErrorMessage($_return,Yii::app()->user->AccountId,Yii::app()->user->id,$resArray['TRANSACTIONID']);
      
	 	if(is_array($message) && isset($message['success'])){
		//Yii::app()->user->AccountId = $message['account_id'];
		//Helper::send_mail_message(Helper::param('EMAIL_CS'),Helper::param('EMAIL_CS'),'Charged from batam by Paypal ' ,"Account Id :".Yii::app()->user->AccountId."\nCustomer Id :".Yii::app()->user->id." \nAmount :".$paymentAmount."\n Transaction ID :".$message['transaction_id']);

	 	//save data sqlserver					
	 	
	 	
			$this->redirect(array('Customer/PaymentHistory'));	
	 	}
	  
	    $this->render('paypal_complete',array(
	    	'message' => $message
	    ));
	}

	/**
	 * methodDescription.
	 *
	 * @return returnType returnDescription
	 */
	public function actionPaymentError() {
		$message = null;
		$res     = Yii::app()->session->get('reshash');

		if(is_array($res)){
			$message.="Account Id :".Yii::app()->user->getState("customerID")." \nAmount :".Yii::app()->session->get('TotalAmount')."\n";
			foreach($res as $key => $value){
				$message.= $key." : ".$value."\n";
			}
			//Helper::send_mail_message(Helper::param('EMAIL_CS'),Helper::param('EMAIL_CS'),'Error from batam by Paypal ' ,$message);
		}
		$this->render('paypal_error');
	}

	/**
	 * Paypal return url.
	 *
	 * @return renderView
	 */
	public function actionPaymentReturnUrl() 
	{

		$resArray=Yii::app()->session->get('resArray');

		if(!isset($_GET['token']) || $_GET['token'] != 	 $resArray['TOKEN'] ){
			$this->redirect(array('Customer/summary', 'lang' => $this->language));
		}
			
		$token    = urlencode( $_GET['token']);
		$nvpstr   = "&TOKEN=".$token;
		$p        = new Paypal();
		$resArray = $p->hash_call("GetExpressCheckoutDetails",$nvpstr);

		Yii::app()->session['reshash']=$resArray;
		$ack = strtoupper($resArray["ACK"]);

		if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING'){

			Yii::app()->session['token']       = $token;
			Yii::app()->session['payer_id']    = $_GET['PayerID'];
			Yii::app()->session['TotalAmount'] = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
			
			//QT261 Lưu thông tin đến oracle database. Thông báo paypal thành công
			$model = new TblCustomerPayment;
			$model->customerID      = Yii::app()->user->getState('customerID');
			$model->seqNo           = TblCustomerPayment::getSeqNo($model->customerID);
			$model->paymentMethodID = 13;
			$model->chargedAmount   = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
			$model->createdDate     = date('Y-m-d H:i:s');
			$model->chargedBy       = 'USER SITE';
			
			$dbTransaction = Yii::app()->db->beginTransaction();
			
			try
			{
				if($model->save(false))
				{
					$orcTransaction = Yii::app()->orcdb->beginTransaction();
					
					try
					{
						$subscriber_id = Yii::app()->user->getState('accountNumber');
						$amount        = $model->chargedAmount;
						$date          = date('m/d/Y H:i:s');

						$sql           = "UPDATE USER_DEF SET OUTSTANDING_BALANCE = OUTSTANDING_BALANCE + '$amount'  WHERE USER_ID = '$subscriber_id'";
						Yii::app()->orcdb->createCommand($sql)->execute();
						
						$sql           ="UPDATE user_def SET balance = balance + '$amount', ACT_DATE = SYSDATE WHERE user_id = '$subscriber_id'";
						Yii::app()->orcdb->createCommand($sql)->execute();
						
						$payment = new PAYMENT;
						$payment->PAYMENT_ID     = new CDbExpression('PAYMENT_ID_SEQ.NextVal');
						$payment->PAYER_ID       = $subscriber_id;
						$payment->RECEIPTER      = 'Bao';
						$payment->DESCRIPTION    = 'No description';
						$payment->PAYMENT_DATE   = date('m/d/Y H:i:s');
						$payment->PAYER_ID_TYPE  = 4;
						$payment->PAYMENT_AMOUNT = $amount;
						$payment->PAYMENT_TYPE   = 4;
						$payment->CHECK_NO       = 0;
						
						$ok = $payment->save(false);
						
						if(!$ok)
						{
							throw new CDbException('Save payment fail!');
						}
						
						$orcTransaction->commit();
					}
					catch(CDbException $e)
					{
						$orcTransaction->rollBack();
						throw new CDbException($e->getMessage());
					}
					
					$dbTransaction->commit();
				}
				else 
				{
					Yii::app()->user->setFlash('makepayment-error', "Paypal Transaction error!");
					$this->redirect(array('Customer/makePayment', 'lang' => $this->language));
				}	
			}
			catch(CDbException $e)
			{
				$dbTransaction->rollBack();
				Yii::app()->user->setFlash('makepayment-error', $e->getMessage());
				$this->redirect(array('Customer/makePayment', 'lang' => $this->language));
			}
			
			$this->redirect(array('Customer/PaymentHistory', 'lang' => $this->language));
			
//			$this->render('paypal_return',array(
//					'res' => $resArray
//			));

		}
		else
		{
			$this->redirect(array('Customer/PaymentError', 'lang' => $this->language));
		}
	}

	/**
	 * methodDescription.
	 *
	 * @return returnType returnDescription
	 */
	public function actionPaymentCancel() {
		$resArray=Yii::app()->session->get('resArray');
		if(!isset($_GET['token']) || $_GET['token'] != 	 $resArray['TOKEN'] ){
			$this->redirect(array('Customer/summary'));
		}
		$this->render('paypal_cancel');
	}
	
	/**
	 * @return json loadCustomer
	 */
	public function actionAjaxLoadCustomer() 
	{
		
	    $customerID = Yii::app()->user->getState('customerID');
	    
	    if($customerID == null || (!Yii::app()->request->isAjaxRequest ))
	    {
	    	throw new CHttpException(403, "The requested page does not exist.");
	    }
	    
	    $customer = TblCustomerProfile::model()->findByAttributes(array('customerID' => $customerID));
	    if($customer)
	    {
	    	header('Content-type: application/json');
			$customer->loginID='';
			$customer->password='';
			$customer->email='';
			echo CJSON::encode($customer);
	    }
	    else 
	    {
	    	echo CJSON::encode(array('success' => false));
	    }
	   	Yii::app()->end();
	}
}